package com.dunjx.rabbitMq.simple;

import com.rabbitmq.client.*;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * 简单模式
 * 消费者
 */
@Slf4j
public class Consumer {
//https://www.bilibili.com/video/BV1dX4y1V73G?p=12&spm_id_from=pageDriver
    public static void main(String[] args) {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        connectionFactory.setHost("39.103.219.84");
        connectionFactory.setVirtualHost("/djx");


        Connection connection = null; // 连接

        Channel channel = null; // 通道
        https://www.bilibili.com/video/BV1dX4y1V73G?p=18&spm_id_from=pageDriver
        try {
            connection = connectionFactory.newConnection("Simple_Provider");

            channel = connection.createChannel();
            channel.basicConsume("queue06", true, new DeliverCallback() {
                @Override
                public void handle(String s, Delivery delivery) throws IOException {
                    System.out.println("收到消息后是：" + new String(delivery.getBody(), "UTF-8"));
                }
            }, new CancelCallback() {
                @Override
                public void handle(String s) throws IOException {
                    System.out.println("接受失败了");
                }
            });

            // 程序不往下执行 阻断
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (channel != null&&channel.isOpen()) {
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }

            }

            if (connection!=null && connection.isOpen()){
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
